package com.example.stujava.module.socked.tcp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public static void main(String[] args) {
        int serverPort = 10001;
        ServerSocket serverSocket = null;
        Socket socket = null;
        FileOutputStream fos = null;
        InputStream is = null;
        try {
            //连接
            serverSocket = new ServerSocket(serverPort);
            //接受
            socket = serverSocket.accept();
            System.out.println("客户端信息：" + socket.getInetAddress().getHostAddress() + ":" + socket.getPort());
            //获取流
            is = socket.getInputStream();
            //创建输出的文件夹
            File file = new File("D:\\file\\receive\\new.jpg");
            fos = new FileOutputStream(file);
            //通过输入流获取byte[],输出到file
            byte[] bytes = new byte[10 * 1024];
            int length;
            while ((length = is.read(bytes)) != -1) {
                fos.write(bytes, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if (socket != null) {
                try {
                    socket.shutdownInput();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (serverSocket != null) {
                    try {
                        serverSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        }

    }
}
